What is @smithy/util-waiter?
@smithy/util-waiter is a utility package designed to help with implementing waiters in JavaScript applications. Waiters are used to poll for a resource to reach a desired state, which is particularly useful in scenarios involving asynchronous operations or state transitions.
What are @smithy/util-waiter's main functionalities?
Waiter Configuration
This feature allows you to configure a waiter with specific parameters such as minimum and maximum delay. The `createWaiter` function is used to create a waiter that will poll the `checkState` function until the desired state is reached.
const { createWaiter, WaiterState } = require('@smithy/util-waiter');
const waiterConfig = {
minDelay: 2,
maxDelay: 120,
};
const checkState = async () => {
// Logic to check the state of the resource
return { state: WaiterState.SUCCESS };
};
const waiter = createWaiter(waiterConfig, checkState);
waiter().then(() => console.log('Resource reached the desired state.')).catch((err) => console.error('Failed to reach the desired state:', err));
Custom Retry Logic
This feature allows you to implement custom retry logic by specifying a `retryStrategy` function in the waiter configuration. The `retryStrategy` function determines the delay between retries based on the number of attempts.
const { createWaiter, WaiterState } = require('@smithy/util-waiter');
const waiterConfig = {
minDelay: 2,
maxDelay: 120,
retryStrategy: (attempt) => Math.min(2 ** attempt, 60),
};
const checkState = async () => {
// Logic to check the state of the resource
return { state: WaiterState.RETRY };
};
const waiter = createWaiter(waiterConfig, checkState);
waiter().then(() => console.log('Resource reached the desired state.')).catch((err) => console.error('Failed to reach the desired state:', err));
Other packages similar to @smithy/util-waiter
promise-retry
The `promise-retry` package provides a way to retry a function that returns a promise until it succeeds or a maximum number of retries is reached. It offers customizable retry strategies and is useful for handling transient errors in asynchronous operations. Compared to @smithy/util-waiter, `promise-retry` focuses more on retrying promises rather than waiting for a resource to reach a specific state.
async-retry
The `async-retry` package is another utility for retrying asynchronous functions. It supports custom retry strategies and can be used to handle retries for various types of asynchronous operations. While similar to `promise-retry`, `async-retry` provides more flexibility in defining retry behavior. Unlike @smithy/util-waiter, it does not specifically focus on waiting for a resource state change.